﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Util.Extension;
using Microsoft.AspNetCore.Hosting;
using AntUnion.FrameWork.Util;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class CountryController : BaseController
    {
        private readonly _antunionContext _context;
        private readonly IWebHostEnvironment hostingEnv;
        public CountryController(_antunionContext context, IWebHostEnvironment env) : base(context, env)
        {
            _context = context;
            hostingEnv = env;
        }

        #region 国家列表
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取国家列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in _context.TbCountries.AsNoTracking()
                           select new
                           {
                               id = n.CtId,
                               code = n.CtCode,
                               names = n.CtNameCn,
                               en_name = n.CtNameEn,
                               creator = n.CtCreateEmp,
                               createDate = n.CtCreateTime,
                               update = n.CtUpdateEmp,
                               updateDate = n.CtUpdateTime,
                               status = n.State
                           };
                res.Data = await data.OrderBy(k => k.id).Skip((page - 1) * limit).Take(limit).ToListAsync();
                res.Code = 0;
                res.Count = data.Count();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加国家
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 添加国家
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(TbCountry model)
        {
            ListResult res = new ListResult();
            try
            {
                if (!TbCountryExists(model.CtNameCn))
                {
                    model.CtCreateEmp = User.UserName;
                    model.CtCreateTime = DateTimeUtil.Now;
                    model.State = 0;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Data = "国家名已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑国家信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            TbCountry TbCountry = await _context.TbCountries.FindAsync(id);
            if (TbCountry == null)
            {
                return NotFound();
            }
            return View(TbCountry);
        }
        /// <summary>
        /// 编辑国家信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(TbCountry item)
        {
            ListResult res = new ListResult();
            try
            {
                if (!TbCountryExists(item.CtNameCn, item.CtId))
                {
                    TbCountry model = await _context.TbCountries.FindAsync(item.CtId);
                    if (model != null)
                    {
                        model.CtNameCn = item.CtNameCn;
                        model.CtNameEn = item.CtNameEn;
                        model.CtCode = item.CtCode;
                        model.CtUpdateEmp = User.UserName;
                        model.CtUpdateTime = DateTimeUtil.Now;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Data = "国家不存在";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Data = "国家名已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                TbCountry TbCountry = await _context.TbCountries.FindAsync(id);
                TbCountry.State = intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除国家
        /// <summary>
        /// 删除单个国家
        /// </summary>
        /// <param name="id">国家ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            ListResult res = new ListResult();
            try
            {
                TbCountry TbCountry = await _context.TbCountries.FindAsync(id);

                _context.TbCountries.Remove(TbCountry);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的国家ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            ListResult res = new ListResult();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbCountry> userList = await _context.TbCountries.Where(k => list.Contains(k.CtId)).ToListAsync();
                foreach (TbCountry model in userList)
                {
                    _context.TbCountries.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 删除tup
        /// </summary>
        /// <param name="url">图片路径</param>
        /// <returns></returns>
        [HttpPost, ActionName("DelImg")]
        public JsonResult DelImg(string url)
        {
            ListResult res = new ListResult();
            try
            {
                if (!string.IsNullOrEmpty(url))
                {
                    if (System.IO.File.Exists(hostingEnv.WebRootPath + $@"{url}"))
                    {
                        System.IO.File.Delete(hostingEnv.WebRootPath + $@"{url}");
                    }
                }
                res.Code = 0;
                res.Data = 0;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Names">国家名称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbCountryExists(string Names, int id = 0)
        {
            if (id == 0)
                return _context.TbCountries.Any(e => e.CtNameCn == Names);
            else
                return _context.TbCountries.Any(e => e.CtId != id && e.CtNameCn == Names);
        }
        #endregion
    }
}